package concurrent.lock.readwrite;

import lombok.val;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * ReadWriteLock（读写锁）
 * ReentrantReadWriteLock其读锁是共享锁，其写锁是独占锁。读锁的共享锁可保证并发读是非常高效的
 * 读写，写读，写写的过程是互斥的
 *
 * @author LoneRanger
 */
public class ReadWriteLockTest {

    @Test
    public void test1() throws InterruptedException {
        MyCache myCache = new MyCache();

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> {
                myCache.put(finalI + "", "value" + finalI);
            }, "t" + i).start();
        }

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> {
                String o = (String) myCache.get(finalI + "");
            }, "t" + i).start();
        }

        TimeUnit.SECONDS.sleep(2);

    }

}

/**
 * 拥有读写锁的缓存
 */
class MyCache {
    private volatile Map<String, Object> map = new HashMap<>();

    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void put(String key, Object value) {
        //创建一个写锁
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "线程put值：" + key + "开始");
            TimeUnit.MILLISECONDS.sleep(300);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "线程put值：" + key + "成功");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //解除锁
            readWriteLock.writeLock().unlock();
        }
    }

    public Object get(String key) {
        //创建一个读锁
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "线程get值：" + key + "开始");
            TimeUnit.MILLISECONDS.sleep(300);
            System.out.println(Thread.currentThread().getName() + "线程get值：" + key + "成功");
            return map.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //解除锁
            readWriteLock.writeLock().unlock();
        }
        return null;
    }


}
